#include "qdatabaselistview.h"

#include "../qbaseitemdelegate.h"
#include "../stylehelper.h"

#include <QHeaderView>
#include <QApplication>
#include <QPainter>

QDataBaseListView::QDataBaseListView(QWidget *parent) :
    QTreeWidget(parent)
{
    this->setRootIsDecorated(false);
    this->setAlternatingRowColors(true);
    this->header()->setVisible(false);
    this->setFrameStyle(QFrame::NoFrame);
    this->setItemDelegate(new QBaseItemDelegate);

    connect(this,SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),this,SLOT(item_double_clicked(QTreeWidgetItem*)));
}

void QDataBaseListView::load(const QStringList &list)
{
    clear();
    QStringList l;
    QString group,name;

    QMap<QString,QTreeWidgetItem*> groups;
    QTreeWidgetItem* p;
    QTreeWidgetItem* t;
    QIcon e=StyleHelper::drawIndicatorIcon(this->palette(),this->style());
    foreach(const QString str,list)
    {
        l=str.split(".");
        if(l.size()!=2)
        {
            continue;
        }
        group=l.at(0);
        name=l.at(1);

        p=groups.value(group);
        if(p==NULL)
        {
            p=new QTreeWidgetItem(this);
            p->setText(0,group);
            p->setIcon(0,e);
            p->setData(0,DarkRole,true);
            p->setExpanded(true);
            groups.insert(group,p);
        }
        t=new QTreeWidgetItem(p);
        t->setText(0,name);
        if(m_selects.size()<2)
        {
            item_double_clicked(t);
        }
    }
}

void QDataBaseListView::item_double_clicked(QTreeWidgetItem *item)
{
    if(item->data(0,DarkRole).toBool())
    {
        return;
    }
    QString str=item->parent()->text(0)+"."+item->text(0);
    if(!m_selects.contains(item))
    {
        item->setIcon(0,QIcon(":/images/check.png"));
        m_selects.append(item);
        if(m_selects.size()>2)
        {
            m_selects.first()->setIcon(0,QIcon());
            m_selects.removeFirst();
        }
    }
    emit select(str);
}

void QDataBaseListView::clear()
{
    m_selects.clear();
    QTreeWidget::clear();
}

void QDataBaseListView::drawRow(QPainter *painter, const QStyleOptionViewItem &options, const QModelIndex &index) const
{
    QStyleOptionViewItemV3 opt=options;
    QColor c;
    if(!index.data(DarkRole).toBool())
    {
        c=QColor(BACKGROUND_COLOR);
        opt.palette.setColor(QPalette::AlternateBase,c.lighter(112));
        painter->fillRect(options.rect,c);
    }
    else
    {
        painter->fillRect(options.rect,options.palette.color(QPalette::Dark));
    }
    opt.state &=~ QStyle::State_HasFocus;
    QTreeWidget::drawRow(painter,opt,index);

    QColor color=static_cast<QRgb>(QApplication::style()->styleHint(QStyle::SH_Table_GridLineColor));
    painter->setPen(color);
    painter->drawLine(opt.rect.x(),opt.rect.bottom(),opt.rect.right(),opt.rect.bottom());
}
